package init.utils;

import init.config.Config;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Properties;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.DeploymentBuilder;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class WorkflowUtils {
	private Properties config;
	private ProcessEngine engine;
	private RepositoryService rs;
	
	private String getBpmnDir() throws URISyntaxException{
		String root = WorkflowUtils.class.getResource("/").toURI().getPath();
		return root + Config.BPMN_PATH;
	}

	private Collection<File> getBpmnFiles() throws URISyntaxException{
		return FileUtils.listFiles(new File(this.getBpmnDir()), Config.BPMN_SUFFIX, true);
	}
	
	private void init() throws Exception{
		config = ConfigUtils.parseConfig();
		ProcessEngineConfiguration p = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration();
		p.setJdbcDriver(config.getProperty(Config.DRIVER));
		p.setJdbcUrl(config.getProperty(Config.URL));
		p.setJdbcUsername(config.getProperty(Config.USER));
		p.setJdbcPassword(config.getProperty(Config.PASSWORD));
		engine = p.buildProcessEngine();
		rs = engine.getRepositoryService();
	}
	
	public static WorkflowUtils newInstance() throws Exception{
		WorkflowUtils w = new WorkflowUtils();
		w.init();
		return w;
	}
	
	public void deploy() throws IOException, URISyntaxException{
		DeploymentBuilder d = rs.createDeployment().name(config.getProperty(Config.WORKFLOW_DEPLOY_NAME));
		for(File f : this.getBpmnFiles()){
			FileInputStream input = null;
			try{
				input = FileUtils.openInputStream(f);
				d.addInputStream(f.getName(), input);
			}finally{
				IOUtils.closeQuietly(input);
			}
		}
		d.deploy();
	}
}
